"""
    https://binance-docs.github.io/apidocs/spot/cn/#websocket
"""
import json
import logging
import sys
from datetime import datetime
from websockets.sync.client import connect

logging.basicConfig(
    stream=sys.stdout, level=logging.INFO, format="%(asctime)s-%(levelname)s-%(message)s"
)


class BinanceSpotFeed(object):
    def __init__(self, callback):
        self.callback = callback
        self.subscribed = list()

    @staticmethod
    def seed_message(ws, message):
        logging.info(f"SendMessage: {message}")
        ws.send(json.dumps(message))

    def on_open(self, ws):
        self.seed_message(ws, {
            "method": "SUBSCRIBE",
            "params": ["!ticker@arr"],
            "id": None
        })

    def on_ping(self, ws, msg):
        if "ping" in msg:
            self.seed_message(ws, msg["ping"])

    def on_ticker(self, data):
        self.callback({
            "datetime": datetime.fromtimestamp(data["O"] / 1000), "symbol": data["s"],
            "open": float(data["o"]), "high": float(data["h"]), "low": float(data["l"]), "close": float(data["c"]),
            "volume": float(data["v"]), "amount": float(data["q"])
        })

    def on_data(self, msg):
        if "stream" in msg:
            if msg["stream"] == "!ticker@arr":
                for item in msg["data"]:
                    self.on_ticker(item)

    def on_message(self, ws, msg):
        msg = json.loads(msg)
        self.on_ping(ws, msg)
        self.on_data(msg)

    def start(self):
        with connect("wss://stream.yshyqxx.com/stream") as ws:
            self.on_open(ws)
            while True:
                message = ws.recv(timeout=60)
                self.on_message(ws, message)
